/* Copyright (c) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/


/**
 * osde Namespace contains helper functions and class constructors
 */
var osde = {
  console_ : null,
  log : function(msg) {
    if (this.console_ == null) {
      this.console_ = Components.classes["@mozilla.org/consoleservice;1"].
          getService(Components.interfaces.nsIConsoleService);
    }
    this.console_.logStringMessage(msg);
  },
  
  bind : function(func, obj) {
    return function() {
      func.apply(obj, arguments);
    };
  },
};

/**
 * class osde.LocationObserver 
 * 
 * Handles events given when the location bar changes
 */ 
osde.LocationObserver = function() {};
osde.LocationObserver.prototype = {
  QueryInterface : function(aIID) {
   if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
       aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
       aIID.equals(Components.interfaces.nsISupports))
     return this;
   throw Components.results.NS_NOINTERFACE;
  },

  onLocationChange : function(progress, request, uri) {
    var evt = document.createEvent("Event");
    evt.initEvent("locationchanged", true, false);
    evt.uri = uri;
    document.dispatchEvent(evt);
  },

  onStateChange : function(progress, request, flag, status) {
    if(flag & (Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT |
               Components.interfaces.nsIWebProgressListener.STATE_START)) {
      request.QueryInterface(Components.interfaces.nsIChannel);
      var evt = document.createEvent("Event");
      evt.initEvent("prelocationchanged", true, false);
      evt.uri = request.URI;
      document.dispatchEvent(evt);
    }
  }, 

  onProgressChange : function() {},
  onStatusChange : function() {},
  onSecurityChange : function() {},
  onLinkIconAvailable : function() {}
};
  
/**
 * class osde.UrlParser
 * 
 * Parses container urls and determines information from them
 */
osde.UrlParser = {
  regexIsOrkutUrl_ : /^http:\/\/sandbox\.orkut\.com/,
  regexHasBpc_ : /bpc=1/,
  regexGadgetServerUrl_ : /\/46\/o\/ig/,
  modes : {
    OTHER : 0,
    CANVAS : 1,
    PROFILE : 2
  },
  isOrkutUrl : function(url) {
    var result = url.match(this.regexIsOrkutUrl_);
    return (result != null);
  },
  isBpcUrl : function(url) {
    var result = url.match(this.regexHasBpc_);
    return (result != null);
  },
  isGadgetServerUrl : function(url) {
    var result = url.match(this.regexGadgetServerUrl_);
    return (result != null);
  },
  getMode : function(url) {
    var retval = null;
    retval = osde.UrlParser.modes.OTHER;
    return retval;
  }
};

/**
 * class osde.Controller
 *
 * OpenSocial Developer's Extension controller
 */
osde.Controller = function() {
  this.locationListener_ = new osde.LocationObserver();
  document.addEventListener("locationchanged",
    osde.bind(this.locationChanged, this), false, true);
  document.addEventListener("prelocationchanged",
    osde.bind(this.preLocationChanged, this), false, true);
};
osde.Controller.prototype = {
  locationUrl_ : null,
  locationListener_ : null,

  init : function() {
    gBrowser.addProgressListener(this.locationListener_,
      Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
  },
  
  destroy : function() {
    gBrowser.removeProgressListener(this.locationListener_);
  },
  
  preLocationChanged : function(evt) {
    var uri = evt.uri;
    osde.log("preLocationChanged: " + uri.spec);
    if (this.locationUrl_ != uri.spec) {
      this.locationUrl_ = uri.spec;
      if (osde.UrlParser.isOrkutUrl(uri.spec) && 
          !osde.UrlParser.isBpcUrl(uri.spec) &&
          !osde.UrlParser.isGadgetServerUrl(uri.spec)) {
        var sep = "?";
        if (uri.spec.indexOf("?") > -1) {
          sep = "&";
        }
        gBrowser.loadURIWithFlags(uri.spec + sep + "bpc=1",
            Components.interfaces.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY | 
            Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE,
          null,
          null);
      }
    }
  },

  locationChanged : function(evt) {
    var uri = evt.uri;
    osde.log("locationChanged: " + uri.spec);
    if (this.locationUrl_ != uri.spec) {
      this.locationUrl_ = uri.spec;
      if (osde.UrlParser.isOrkutUrl(uri.spec)) {
        this.enteredOrkut();
      } else {
        this.leftOrkut();
      }
    }
  },

  enteredOrkut : function() {
    osde.log("Entered Orkut");
  },

  leftOrkut : function() {
    osde.log("Left Orkut");
  }
};


//Create a controller instance and wire it to the window
var ctrl = new osde.Controller();
window.addEventListener("load", function() { ctrl.init(); }, false);
window.addEventListener("unload", function() { ctrl.destroy(); }, false);




